package com.aaa.until;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.sound.midi.Soundbank;
import javax.xml.crypto.Data;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Mickey
 * @date ：Created in 2022/11/2 15:40
 * @description：
 * @modified By：
 * @version:
 */
public class JWTUtil {
    private static String sign = "cmq-aaa";
    //生成token方法
    public static String createJWT(Map map){
        //定义头信息
        Map<String, Object> head = new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","IWT");
        //定义颁发时间
        Date iat = new Date();
        //定义过期时间
        Calendar expire = Calendar.getInstance();
        expire.set(Calendar.SECOND,7200);
        Date expireTime = expire.getTime();

        String token = JWT.create()
                //头信息
                .withHeader(head)
                //设置搬颁发时间
                .withIssuedAt(iat)
                //设置过期时间
                .withExpiresAt(expireTime)
                //自定义内容
                .withClaim("Login", map)
                //签名
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    //验证token是否有效
    public static boolean verifyToken(String token){
        //获取一个JWT校验对象
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        try{
            //调用校验功能
            build.verify(token);
            return true;
        }catch (Exception e){
            System.out.println("token无效");
            return false;
        }
    }
    //从token中获取相关载荷内容
    public static Map<String,Object> getTokenChaim(String token){
        //获取一个JWT校验对象
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        //调用校验功能
        DecodedJWT verify = build.verify(token);
        Claim loginInfo = verify.getClaim("loginInfo");
        return loginInfo.asMap();
    }
}
